#【云片短信通道】发送短信
require 'json'
class SmsWorker < ApplicationController
	include Sidekiq::Worker
	sidekiq_options queue: 'sms'


	# 验证码
	def perform(mobile, sms_type)
		params ={}
		yunpian_config = YAML.load_file("#{Rails.root.to_s}/config/settings/services/yunpian.yml")
		apikey = yunpian_config["defaults"]["apikey"]
		expired = yunpian_config["defaults"]['expired']
		company_name = yunpian_config["defaults"]['company_name']
		sn_code = SecureRandom.random_number.to_s[-6, 6]
		attributes = {
			mobile: mobile,
			sms_type: 'sn_code',
			content_hash: {source: sms_type, sn_code: sn_code}.to_json,
			expired_at: Time.now + expired
		}
		sms_log = SmsLog.create(attributes)
		if %w(signup bind_mobile).include?(sms_type)
			text = "【#{company_name}】您的验证码是#{sn_code}"
		elsif %w(modify_password reset_password).include?(sms_type)
			text = "【#{company_name}】正在找回密码，您的验证码是#{sn_code}"
		end

		params[:apikey] = apikey
		params[:mobile] = mobile
		params[:text] = text
			
		begin
			#调用云片的短信api
			result = ActiveSupport::JSON.decode(Yunpian::SmsClient.send_to(params).body)
			result = {status: result["code"] == 0 ? 'send' : 'failed'}

		rescue
			result = {status: 'failed'}
		ensure
			sms_log.update(result)
		end
	end
end
